from datetime import datetime
from app import db

# 超市表模型
class Supermarket(db.Model):
    __tablename__ = 'tb_supermarket'
    
    market_id = db.Column(db.BigInteger, primary_key=True, autoincrement=True, comment='超市ID(主键)')
    name = db.Column(db.String(100), nullable=False, comment='超市名称')
    address = db.Column(db.String(255), comment='地址')
    longitude = db.Column(db.Numeric(10, 6), comment='经度')
    latitude = db.Column(db.Numeric(10, 6), comment='纬度')
    image_url = db.Column(db.String(255), comment='超市图片URL')
    business_hours = db.Column(db.String(100), comment='营业时间')
    phone = db.Column(db.String(20), comment='联系电话')
    description = db.Column(db.Text, comment='超市描述')
    rating = db.Column(db.Numeric(2, 1), default=5.0, comment='评分(1-5)')
    sale_count = db.Column(db.Integer, default=0, comment='销售总量')
    status = db.Column(db.Integer, default=1, comment='状态(0-关闭,1-营业)')
    create_time = db.Column(db.DateTime, default=datetime.now, comment='创建时间')
    update_time = db.Column(db.DateTime, default=datetime.now, onupdate=datetime.now, comment='更新时间')
    
    # 关联
    boxes = db.relationship('BlindBox', back_populates='supermarket', lazy='dynamic', foreign_keys='BlindBox.market_id')
    orders = db.relationship('Order', back_populates='supermarket', lazy='dynamic')
    
    def __repr__(self):
        return f'<Supermarket {self.name}>'
    
    def to_dict(self):
        """转换为字典，用于API响应"""
        return {
            'market_id': self.market_id,
            'name': self.name,
            'address': self.address,
            'longitude': float(self.longitude) if self.longitude else None,
            'latitude': float(self.latitude) if self.latitude else None,
            'image_url': self.image_url,
            'business_hours': self.business_hours,
            'phone': self.phone,
            'description': self.description,
            'rating': float(self.rating) if self.rating else 5.0,
            'sale_count': self.sale_count,
            'status': self.status,
            'create_time': self.create_time.strftime('%Y-%m-%d %H:%M:%S') if self.create_time else None,
            'update_time': self.update_time.strftime('%Y-%m-%d %H:%M:%S') if self.update_time else None,
            'box_count': len(self.boxes) if hasattr(self, 'boxes') else 0
        } 